﻿using Microsoft.EntityFrameworkCore;
using Project.Net.Domain.UserLogin;
using Project.Net.Infra.Data;
using Project.Net.Infra.Entity;

namespace Project.Net.Infra.UserLogin
{
    /// <summary>
    /// 
    /// </summary>
    public class UserRepository : IUserRepository
    {
        private readonly AppDbContext _db;
        public UserRepository(AppDbContext db)
        {
            _db = db;
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="user"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task AddAsync(User user)
        {
            var addModel = new UserModel()
            {
                Email = user.Email,
                PasswordHash = user.PasswordHash,
                Username = user.Username
            };
            await _db.UserModels.AddAsync(addModel);
            await _db.SaveChangesAsync();
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="email"></param>
        /// <returns></returns>
        public async Task<bool> ExistsByEmailAsync(string email)
        {
            return await _db.UserModels
            .AnyAsync(u => u.Email == email);
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="username"></param>
        /// <returns></returns>
        public async Task<bool> ExistsByUsernameAsync(string username)
        {
            return await _db.UserModels
            .AnyAsync(u => u.Username == username);
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="email"></param>
        /// <returns></returns>
        public async Task<User?> GetByEmailAsync(string email)
        {
            var model = await _db.UserModels.FirstOrDefaultAsync(u => u.Email == email);
            if (model == null)
            {
                return null;
            }
            return new User(model.Username, model.PasswordHash, model.Email,model.Id);
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="username"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<User?> GetByUsernameAsync(string username)
        {
            var model = await _db.UserModels.FirstOrDefaultAsync(u => u.Username == username);
            if (model == null)
            {
                return null;
            }
            return new User(model.Username, model.PasswordHash, model.Email,model.Id);

        }

        public async Task<User?> GetUserInfoById(int userId)
        {
            var model= _db.UserModels.FirstOrDefault(u => u.Id == userId);
            if (model == null)
            {
                return null;
            }
            return new User(model.Username, model.PasswordHash, model.Email,model.Id);
        }
    }
}
